package config

import (
	"context"
	"fmt"
	"go-chain-data/config/setting"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"log"
)

func NewDBEngine(dbConfig *setting.DbConfig) (*mongo.Client, error) {
	clientOptions := options.Client().ApplyURI("mongodb://" + dbConfig.Username + ":" + dbConfig.Pwd + "@" + dbConfig.Host + "/?authSource=" + dbConfig.DbName)

	// 连接到MongoDB
	client, err := mongo.Connect(context.Background(), clientOptions)
	if err != nil {
		log.Fatal(err)
	}

	// 检查连接
	err = client.Ping(context.Background(), nil)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println("成功连接到MongoDB")
	return client, nil
}
